﻿using Microsoft.AspNetCore.SignalR;
using System.Reflection;

namespace SingalR.Server.Hubs
{
    public class Chat:Hub
    {
        

        //被客户端调用-1
        public void CallByClient(string msg)
        {
            Console.WriteLine("方法1:"+msg);
          
        }
        //被客户端调用有返回值-2
        public string CallByClientWithReturnValue(string msg)
        {
            Console.WriteLine("方法2有返回值:" + msg);
            return MethodInfo.GetCurrentMethod()?.Name + "";
        }

        //方法-3被客户端调用 并向Hub发送调用者的id
        public string CallClient(string msg)
        {
            Console.WriteLine("方法3客户端传来数据" + msg);
            Clients.Caller.SendAsync("CallByHub", $"{Context.ConnectionId}{msg}");//返回调用者的id
            return MethodInfo.GetCurrentMethod()?.Name + "";
        }



        //方法4-被客户端调用 全员发送
        public string CallAllClients(string msg)
        {
            Console.WriteLine("全员发送" + msg);
            Clients.All.SendAsync("CallByHub", msg);//向所有连接的客户端发送信息
            return MethodInfo.GetCurrentMethod()?.Name + "";
        }
        //方法5-被客户端调用 除自身以外发送
        public string CallOtherClients(string token,string par,string machine)
        {

            try
            {
                Clients.Others.SendAsync("CallByHub",token,par,machine );//向向出自身以外发送
                return "ok";
            }catch (Exception ex)
            {
               return ex.Message;
            }
    
        }

        //方法6-被客户端调用  加入分组  并向指定组别发送
        public void RegisterToGroup(string grpName)
        {
            Groups.AddToGroupAsync(Context.ConnectionId, grpName);//将连接者添加到分组
        }
        public void SendToGroup(string name)
        {
            Console.WriteLine("分组发送" + name);
            Clients.Group(name).SendAsync("CallByHub", $"{Context.ConnectionId}");//向向出自身以外发送
        ;
        }

        //方法7-指定发送id发送
        public void SendToClient(string connid)
        {
            Console.WriteLine("指定id发送" );
            Clients.Client(connid).SendAsync("CallByHub", $"{Context.ConnectionId}");//指定id发送
    
        }


        // 使用静态集合来存储连接者的ID
        private static HashSet<string> connectedIds = new HashSet<string>();
    }
}
